package com.zzw.service.Impl;

import com.zzw.bean.EmailVerificationCode;
import com.zzw.service.EmailService;
import com.zzw.service.RedisCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisCacheService redisCacheService;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${spring.mail.default-encoding}")
    private String defaultEncoding;

    @Value("${email.code.expiration}")
    private int codeExpiration;

    // Redis键前缀，用于存储验证码
    private static final String EMAIL_CODE_PREFIX = "email_code:";

    @Override
    public String sendVerificationCode(String to) {
        // 生成6位随机数字验证码
        String code = generateVerificationCode();

        // 创建Redis键
        String redisKey = EMAIL_CODE_PREFIX + to;

        // 保存验证码到Redis
        redisCacheService.setCache(redisKey, code, codeExpiration);

        // 发送验证码邮件
        try {
            MimeMessage message = mailSender.createMimeMessage();
            // 第三个参数指定字符编码，解决中文乱码问题
            MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name());
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject("验证码");

            String content = "<!DOCTYPE html>"
                    + "<html>"
                    + "<head>"
                    + "<meta charset=\"UTF-8\">"
                    + "<title>验证码</title>"
                    + "</head>"
                    + "<body>"
                    + "<h2>您的验证码是：" + code + "</h2>"
                    + "<p>验证码有效期为" + (codeExpiration / 60) + "分钟，请勿泄露给他人。</p>"
                    + "</body>"
                    + "</html>";

            helper.setText(content, true);
            mailSender.send(message);
            return code;
        } catch (MessagingException e) {
            throw new RuntimeException("发送邮件失败", e);
        }
    }

    @Override
    public boolean verifyCode(String email, String code) {
        // 创建Redis键
        String redisKey = EMAIL_CODE_PREFIX + email;
        
        // 从Redis获取验证码
        String storedCode = (String) redisCacheService.getCache(redisKey);
        
        // 检查验证码是否存在
        if (storedCode == null) {
            return false;
        }
        
        // 检查验证码是否匹配
        boolean isValid = storedCode.equals(code);
        
        // 如果验证成功，从Redis中删除验证码
        if (isValid) {
            redisCacheService.deleteCache(redisKey);
        }
        
        return isValid;
    }

    /**
     * 生成6位随机数字验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}
